﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceWarranty;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.CustomerService.Controllers
{
    public class SortingWorkOrderController : BaseController
    {
        // GET: SortingWorkOrder
        public ActionResult Index()
        {
            return View();
        }
        #region 获取报案工单任务列表数据
        /// <summary>
        /// 获取报案工单任务列表数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Index(InsuranceWarrantyRecordModel model)
        {
            var total = 0;
            var list = ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total)
                .Include(o => o.SystemUser).Include(o => o.InsuranceOrder).AsNoTracking().ToList().Select(o =>
                {
                    var expressInfo = o.InsuranceWarrantyRecordExpressInfo != null
                        ? o.InsuranceWarrantyRecordExpressInfo.FirstOrDefault(express => express.ExpressSendByWhoType == (byte)ExpressSendByWhoType.UserSendToPartitionCenter) : null;
                    return new
                    {
                        o.ID,
                        o.InsuranceOrderId,
                        o.WarrantyRecordNo,
                        o.Reporter,
                        o.ReporterPhone,
                        o.Status,
                        StatusDesc =
                            ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.GetStatusName(o.Status),
                        o.CreateTime,
                        o.LastModifyTime,
                        o.InsuranceOrder.InsuranceCompany,
                        o.InsuranceOrder.InsuranceCompanyBranch,
                        o.SortingCenterID,
                        SortingCenterName = o.SortingCenterID.HasValue ? o.SortingCenter.SortingCenterName : "",
                        SendExpressName = expressInfo != null ? EnumHelper.Instance.GetDescription(typeof(ExpressEnums), expressInfo.ExpressCompanyID) : EnumHelper.Instance.GetDescription(typeof(ExpressEnums), o.SendExpress),
                        SendExpressNo = expressInfo != null ? expressInfo.ExpressNo : o.SendExpressNo,
                        ExpressStatus = expressInfo != null ? expressInfo.ExpressStatus : ""
                    };
                });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion
        public ActionResult Detail(int id)
        {
            var insuranceWarrantyRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(id);
            return View(insuranceWarrantyRecord);
        }

        #region 分拣中心保存维修信息

        [HttpPost]
        [ValidateInput(true)]
        public ActionResult SaveSortingCenterAuditInsuranceWarrantyRecord(InsuranceWarrantyRecord model, IList<InsuranceWarrantyRecordAuditInfo> insuranceWarrantyRecordAuditInfo, int saveType)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Save
            };

            var warrantyRecordService = ServiceFactory.InsuranceWarrantyRecordServiceInstance;
            var auditInfoService = ServiceFactory.InsuranceWarrantyRecordAuditInfoServiceInstance;

            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    var entity = warrantyRecordService.LoadByID(model.ID);
                    entity.LastModifyTime = DateTime.Now;
                    entity.LastModifyBy = CurrentUser.UserAccount;
                    //维修服务商
                    entity.ServiceProviderBranchId = model.ServiceProviderBranchId;
                    //密码
                    entity.LockScreenTypeID = model.LockScreenTypeID;
                    entity.LockScreenContent = model.LockScreenContent;
                    if (!model.ServiceProviderBranchId.HasValue)
                    {
                        responseResult.Message = "请选择维修服务商！";
                    }
                    else
                    {
                        if (saveType == 2)
                        {
                            //派单人
                            entity.SortingCenterSendOrderUserID = CurrentUser.ID;
                            entity.SendOrderTime = DateTime.Now;

                            entity.Status = (byte) InsuranceWarrantyStatus.SendToRepair;
                            if (model.Status != entity.Status)
                            {
                                //获取父级状态
                                var service = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance;
                                InsuranceWarrantyRecordStatus newStatusInfo = service.LoadEntities(t => t.StatusCode == entity.Status).FirstOrDefault();

                                //记录流程日志
                                InsuranceWarrantyRecordStatus oldStatusInfo = service.LoadEntities(t => t.StatusCode == model.Status).FirstOrDefault();
                                var insuranceWarrantyRecordController = new InsuranceWarrantyRecordController();
                                insuranceWarrantyRecordController.WriteProcessLog(oldStatusInfo, newStatusInfo, null, model.ID);
                            }
                        }
                        responseResult.Success = warrantyRecordService.UpdateEntities(entity);
                    }
                    if (responseResult.Success)
                    {
                        if (insuranceWarrantyRecordAuditInfo!=null && insuranceWarrantyRecordAuditInfo.Count()> 0)
                            responseResult.Success = auditInfoService.Save(model.ID, insuranceWarrantyRecordAuditInfo,
                                CurrentUser.UserAccount);
                    }
                    if (responseResult.Success)
                    {
                        ts.Complete();
                    }
                    else
                    {
                        ts.Dispose();
                    }
                }
                catch (Exception e)
                {
                    ts.Dispose();
                }
            }
            return Json(responseResult);
        }
        #endregion
    }
}